package com.dayatang.android.Activity;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.ExecutionException;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.model.CategorySeries;
import org.achartengine.renderer.DefaultRenderer;
import org.achartengine.renderer.SimpleSeriesRenderer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.dayatang.android.Task.BaseTask;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


public class SpecialtyOutputallActivity extends BaseActivity {

	private final static int StartDATE_DIALOG = 0;
	private final static int EndDATE_DIALOG = 1;
	
	private String[] specialtyName = null;
	private String[] specialtyOutput = null;
	
	private String fromDate = null;
	private String toDate = null;
	
	private Calendar c = null;

	private View view;
	private LinearLayout layout;

	private Button submitBtn;
	private EditText fromEditText,toEditText;

	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.project_outputall_activity);
		
		InitEditText();
		InitBtn();

		layout = (LinearLayout) findViewById(R.id.project_outputall_layout);
		
		Init();
	}
	
	private void Init(){
		
		specialtyName = null;
		specialtyOutput = null;
		
		InitData();
	}

	 final Handler handler = new Handler() {
	        public void handleMessage(Message msg) {
	            switch (msg.what) {
	            case 1:
	            	Init();
	                break;
	            }
	            super.handleMessage(msg);
	        }
	};
	
	private void InitBtn(){
		
		submitBtn = (Button) findViewById(R.id.project_outputall_submitBtn);
		submitBtn.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View arg0) {
				if(checkEidt()){
					Message message = new Message();
		            message.what = 1;
		            handler.sendMessage(message);
				}
			}
		});
		
	}
	
	private boolean checkEidt(){
		
		String fromText = fromEditText.getText().toString();
		String toText = toEditText.getText().toString();

		if(fromText.equals("") || toText.equals("")){
			Toast.makeText(this, getString(R.string.reports_alert_noNull), Toast.LENGTH_LONG).show();
			return false;
		}else{
			DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			
			try {
				Date date1 = format.parse(fromText);
				Date date2 = format.parse(toText);
				
				if(date1.after(date2)){
					Toast.makeText(this, getString(R.string.reports_alert_timeBefAft), Toast.LENGTH_LONG).show();
					return false;
				}else{
					return true;
				}
				
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		
		return true;
		
	}
	
	private void InitEditText(){
		
		fromEditText = (EditText) findViewById(R.id.reports_from_data_editText);
		toEditText = (EditText) findViewById(R.id.reports_to_data_editText);
		
		fromEditText.setOnTouchListener(new TextView.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				showDialog(StartDATE_DIALOG);
				return false;
			}
		});
		
		toEditText.setOnTouchListener(new TextView.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				showDialog(EndDATE_DIALOG);
				return false;
			}
		});
		
	}

	
	private void InitData() {
		
		String url = null;
		
		fromDate = fromEditText.getText().toString();
		toDate = toEditText.getText().toString();
		
		if(fromDate == null && toDate == null){
			url = getServerAddress() + "/remote/specialty-outputall.action";
		}else{
			url = getServerAddress() + "/remote/specialty-outputall.action?fromDate="+fromDate+"&toDate="+toDate;
		}
		
		try {
			String result = new BaseTask(this).execute(url).get();

			if (result.equals("error")) {
				Toast.makeText(this,getString(R.string.serverAddress_alert_addressError),Toast.LENGTH_LONG).show();
			} else if (result.equals("NoData")) {
				Toast.makeText(this, getString(R.string.reports_alert_nofind_data),Toast.LENGTH_LONG).show();
				layout.removeAllViews();
			} else if (result != null) {

				JSONArray array = new JSONArray(result);

				specialtyName = new String[array.length()];
				specialtyOutput = new String[array.length()];

				for (int i = 0, len = array.length(); i < len; i++) {

					JSONObject jsonObject = array.getJSONObject(i);
					specialtyName[i] = jsonObject.getString("specialtyName");
					specialtyOutput[i] = jsonObject
							.getString("specialtyOutput");

				}
				
				view = execute(this);
				
				layout.removeAllViews();
				layout.addView(view);

			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	public GraphicalView execute(Context context) {
		int[] values = new int[specialtyOutput.length];

		for (int i = 0, len = specialtyOutput.length; i < len; i++) {
			values[i] = Integer.valueOf(specialtyOutput[i]);
		}
		
		int[] colors = new int[] {Color.YELLOW, Color.CYAN, Color.BLUE,Color.GREEN, Color.MAGENTA,};
		DefaultRenderer renderer = buildCategoryRenderer(colors);
		renderer.setZoomButtonsVisible(true);
		renderer.setChartTitleTextSize(20);
		return ChartFactory.getPieChartView(context,
				buildCategoryDataset("Project budget", values), renderer);
	}

	protected DefaultRenderer buildCategoryRenderer(int[] colors) {
		DefaultRenderer renderer = new DefaultRenderer();
		renderer.setLabelsTextSize(15);
		renderer.setLegendTextSize(15);
		renderer.setMargins(new int[] { 20, 30, 15, 0 });
		for (int i = 0, len = specialtyOutput.length; i < len; i++) {
			SimpleSeriesRenderer r = new SimpleSeriesRenderer();
			r.setColor(colors[i]);
			renderer.addSeriesRenderer(r);
		}
		return renderer;
	}

	protected CategorySeries buildCategoryDataset(String title, int[] values) {
		CategorySeries series = new CategorySeries(title);
		int k = 0;
		for (int value : values) {
			series.add(specialtyName[k] + "," + specialtyOutput[k], value);
			k++;
		}

		return series;
	}
	
	protected Dialog onCreateDialog(int id) {
		
		Dialog dialog = null;
		
		switch(id){
		
			case StartDATE_DIALOG:
				c = Calendar.getInstance();
				dialog = new DatePickerDialog(this, 
						new DatePickerDialog.OnDateSetListener() {
							public void onDateSet(DatePicker view, int year, int monthOfYear,
									int dayOfMonth) {
									
									fromEditText.setText(year + "-" + (monthOfYear+1) + "-" + dayOfMonth);
							}
						}, 
					c.get(Calendar.YEAR), 
					c.get(Calendar.MONTH), 
					c.get(Calendar.DAY_OF_MONTH)
				);
				break;
			
			case EndDATE_DIALOG:
				c = Calendar.getInstance();
				dialog = new DatePickerDialog(this,
						new DatePickerDialog.OnDateSetListener() {
							public void onDateSet(DatePicker view, int year, int monthOfYear,
									int dayOfMonth) {
									toEditText.setText(year + "-" + (monthOfYear+1) + "-" + dayOfMonth);
							}
						}, 
					c.get(Calendar.YEAR), 
					c.get(Calendar.MONTH), 
					c.get(Calendar.DAY_OF_MONTH)
				);
				break;
				
		}
		
		return dialog;
	}

	
}
